package com.indCfeng.minio;

import io.minio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;


/**
 * @author Cfeng
 * @date 2022/8/11
 * Minio服务的核心服务类： 调用MinioClient完成文件上传下载等工作
 * 需要实现ApplicationRunner,这样就可以在引入项目的容器加载时完成自动装载Minio服务
 */

@Service
public class MinioService implements ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinioConfiguration.class);

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfigurationProperties minioConfigurationProperties;

    //程序启动时自动创建bucket
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //不存在就创建
        if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfigurationProperties.getBucket()).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfigurationProperties.getBucket()).build());
            LOGGER.info("{} is created successfully",minioConfigurationProperties.getBucket());
        }
    }
    
    //输入流形式上传文件,对象存储，封装minio的原生方法
    public ObjectWriteResponse uploadObject(String objectName, InputStream inputStream) throws Exception {
        //利用MinIO的PutObjectArgs即可完成build，借助MinioClient的put方法上传
        return minioClient.putObject(PutObjectArgs.builder().bucket(minioConfigurationProperties.getBucket()).object(objectName).stream(inputStream,inputStream.available(),-1).build());
    }

    //从存储桶移除文件
    public void removeObject(String objectName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioConfigurationProperties.getBucket()).object(objectName).build());
    }

    //下载文件
    public InputStream getObject(String objectName) throws Exception {
        //先查看文件状态，再进行获取，也就是先进行stat，再get
        minioClient.statObject(StatObjectArgs.builder().bucket(minioConfigurationProperties.getBucket()).object(objectName).build());
        return minioClient.getObject(GetObjectArgs.builder().bucket(minioConfigurationProperties.getBucket()).object(objectName).build());
    }

    //移除存储桶
    public void removeBucket() throws Exception {
        //先查找是否存在存储桶
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfigurationProperties.getBucket()).build());
        if(found) {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(minioConfigurationProperties.getBucket()).build());
            LOGGER.info("{} removed successfully",minioConfigurationProperties.getBucket());
        } else {
            LOGGER.info("{} does't exist",minioConfigurationProperties.getBucket());
        }
    }
}
